# 使用cookie登录淘宝
import time
from time import sleep

from selenium import webdriver
from selenium.webdriver.chrome.service import Service
from selenium.webdriver.chrome.options import Options

# 打开浏览器
service = Service(r"D:\app\Python38\chromedriver.exe")
chrome_options = Options()
chrome_options.add_experimental_option("detach", True)
# 创建浏览器对象
driver = webdriver.Chrome(options=chrome_options)

"""
需求：使用cookie实现跳过登录
1). 手动登录淘宝，获取cookie
2). 使用获取到的cookie，达到登录目的，然后就可以执行登录之后的操作
"""
# 1. 先访问淘宝页面，确保域名匹配（关键步骤）
driver.get("https://www.taobao.com")
# 等待页面加载
time.sleep(2)

# 2. Cookie字符串
cookie_str = "cookie2=12c6c23f4df37dce7b2d9f63f6cf2d7a; t=c79670c26cbea2ecc64a2bda4a515594; _tb_token_=e7eadb5f76e3e; mtop_partitioned_detect=1; _m_h5_tk=d89329d880cac1f09c4c89cc3071b993_1762264989303; _m_h5_tk_enc=cf44bc91de6de684f09ac5776938c724; thw=xx; arms_uid=62485a75-717e-4a9d-bb51-7be229591e96; xlly_s=1; sca=13b656f3; _samesite_flag_=true; wk_cookie2=1b4a556154880b476c0e3da44e034a7f; sdkSilent=1762285603636; havana_sdkSilent=1762285603636; mt=ci=0_0; cna=XtWQIfYyZSEBASQIiVYGE2A8; 3PcFlag=1762257839456; wk_unb=UNaGu6ZV%2FPsuEQ%3D%3D; sgcookie=E100Y9J8rP3uY3q7YVciQGJmi7Q%2BVvOcuVVP9wh%2F2dABtEexKM%2FIq30TaeMrW5ZMZxeWu9o%2FXgenP7Br0HVKV9sxtW0VDmg9x6%2FZjEF%2B0YclwHo%3D; unb=3613139658; csg=7f278bbe; lgc=tb294159169; cancelledSubSites=empty; cookie17=UNaGu6ZV%2FPsuEQ%3D%3D; dnk=tb294159169; skt=123c37e33fdea9fd; tracknick=tb294159169; _l_g_=Ug%3D%3D; sg=98e; _nk_=tb294159169; cookie1=U7ZvqIvY5kBpDIQPlfAKXBaCfuU0HBDK1lIQ%2FMXQZ8M%3D; uc1=existShop=false&cookie15=U%2BGCWk%2F75gdr5Q%3D%3D&cookie14=UoYY4dvcRSGVEw%3D%3D&cookie16=V32FPkk%2FxXMk5UvIbNtImtMfJQ%3D%3D&pas=0&cookie21=WqG3DMC9Fb5mPLIQo9kR; sn=; uc3=vt3=F8dD2kv%2F1gNdX02gREo%3D&nk2=F5RHqFkvmjC4oJw%3D&lg2=W5iHLLyFOGW7aA%3D%3D&id2=UNaGu6ZV%2FPsuEQ%3D%3D; existShop=MTc2MjI1NzkzMw%3D%3D; uc4=id4=0%40UgGP%2F8BaY8LoFd0OhLYaIr8wIdwC&nk4=0%40FY4MuqKpaaACNHaksVVxNvXgDsPemg%3D%3D; _cc_=VFC%2FuZ9ajQ%3D%3D; _hvn_lgc_=0; havana_lgc_exp=1793361933685; havana_lgc2_0=eyJoaWQiOjM2MTMxMzk2NTgsInNnIjoiN2ZiYmYzYTQ0Y2IyY2M0ZTA4ZWI3NmMwODE3MGIzMjgiLCJzaXRlIjowLCJ0b2tlbiI6IjFHSWg5UndCX2Y4MTVfeHE3d3Q5QU1RIn0; cnaui=3613139658; aui=3613139658; tfstk=glhn3gZblvyI6HfCKUVBKfLqNl9TOWN7D0C827EyQlr1vMCKzzPob0LQv4-IqbqZz9CKwvBuU0nip8l82bYuOfHdwkKQZ4oYZnKvMI3IR5NyDnefb8jzazR84deEgArGgnKvMCE9z67BD2HnDD3aorPz88yPbF47byrr4kyNbr4bauor4RzaRybU8zrz_Vr_z7rr478g_lauauozaF0ZTvX7mDix_3MfDP7tkAcg-Jqq8K1PZffYKouUj_Risyx702rGa_r4zNnjS2KhGVFI6m4xvC5nm2kq4xows62sLVcuhbse77yrBxenIH5uXXUu37yGz_ugTlwjaSRVjPMZJYlIxafzRXhYEowMz_w8_jeq3DbWlVPUz0wjwn1QY4ujGxFDZ1P3UgrdQtJtG_awyfX5FJz_SoELhemDZ1em8FYGhCyU5yOMSFX5FJz_SoLMStWaLPaBs; isg=BHp6kH24x_xMAEuQU75p0bAcy6CcK_4F55IkO4RzSI3adxuxbLrwFRKVxAOrTnad"

# 3. 拆分Cookie字符串为独立键值对，逐个添加
for cookie_item in cookie_str.split('; '):
    # 分割key和value（处理value中可能包含=的情况）
    if '=' in cookie_item:
        key, value = cookie_item.split('=', 1)
        # 构造单个Cookie字典
        single_cookie = {
            'name': key,
            'value': value,
            'domain': '.taobao.com',  # 淘宝的Cookie通用域名
            'path': '/',
            'httpOnly': False,  # 适配于大部分淘宝Cookie
            'secure': False     # 非HTTPS环境也能生效
        }
        try:
            driver.add_cookie(single_cookie)
            print(f"添加成功Cookie: {key}")
        except Exception as e:
            # 部分Cookie可能因格式限制添加失败，不影响整体使用
            print(f"跳过的Cookie {key}: {str(e)[:50]}")

# 4. 刷新页面使Cookie生效
time.sleep(3)
driver.refresh()

time.sleep(3)
# 5. 退出浏览器
driver.quit()